package com.wins.bbs.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;

public final class EncryptUtils {

    public static String genSalt() {
        final Random ran = new Random();
        final StringBuffer sb = new StringBuffer();
        final String str = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM";
        for (int i = 0; i < 32; i++) {
            sb.append(str.charAt(ran.nextInt(62)));
        }
        return sb.toString();
    }

    public static String encrypt(final String pass, final String salt) {
        try {
            final MessageDigest md5 = MessageDigest.getInstance("MD5");
            final byte[] hex = md5.digest((pass + salt).getBytes());
            final StringBuffer buffer = new StringBuffer();
            for (final byte b : hex) {
                final int n = b & 0xff;
                final String str = Integer.toHexString(n);
                if (str.length() == 1) {
                    buffer.append("0");
                }
                buffer.append(str);
            }
            return buffer.toString();
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static boolean verify(final String pass, final String salt, final String userPass) {
        final String encryptPass = encrypt(pass, salt);
        return StringUtils.equals(encryptPass, userPass);
    }
}
